package dev.zeno.booru;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class ViewBooruActivity extends BaseActivity {

	Booru booru;
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		int id = getIntent().getIntExtra("ID", -1);
		if(id == -1)
			finish();
		
		booruDatabase.open();
		booru = booruDatabase.getBooru(id);
		booruDatabase.close();
		ActionBar actionBar = getSupportActionBar();
	    actionBar.setDisplayHomeAsUpEnabled(true);
		
		new GetImageAsyncTask().execute(booru);

	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
	        case android.R.id.home:
	        	finish();
	        	return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }
	
	class GetImageAsyncTask extends AsyncTask<Booru, Void, String>
	{

		@Override
		protected String doInBackground(Booru... params) {
			HttpClient client = new DefaultHttpClient();
			String result = "";
			for(Booru booru: params)
			{
				Log.v("URL", booru.getPostURL());
				HttpGet request = new HttpGet(booru.getPostURL());
				try {
					HttpResponse response = client.execute(request);
					BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
					StringBuilder builder = new StringBuilder();
					for (String line = null; (line = reader.readLine()) != null;) {
					    builder.append(line).append("\n");
					}
					result += response.getStatusLine()+"\n";
					result += builder.toString();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}

			return result;
		}
		
		@Override
		protected void onPostExecute(String result)
		{
			Log.v("ViewBooruActivity", result);
		}
		
	}
}
